#include "ap3216c2.h"
#include "string.h"
#include <stdint.h>
#include <stdio.h>

struct i2c_transfer ap3216;
uint8_t res;

void AP3216_W_Data(uint8_t registerAddr, uint8_t val) {

  memset(&ap3216, 0, sizeof(ap3216));
  ap3216.data = &val;
  ap3216.dataSize = 1;
  ap3216.subaddressSize = 1;
  ap3216.subaddress = registerAddr;
  ap3216.direction = kI2C_Write;
  ap3216.slaveAddress = AP3216_ADDRESS;
  res = i2c_master_transfer(I2C1, &ap3216);
  if (res) {
    printf("Write 失败 \r\n");
  }
}

uint8_t AP3216_R_Data(uint8_t registerAddr) {
  uint8_t data;

  memset(&ap3216, 0, sizeof(ap3216));
  ap3216.data = &data;
  ap3216.dataSize = 1;
  ap3216.subaddressSize = 1;
  ap3216.subaddress = registerAddr;
  ap3216.direction = kI2C_Read;
  ap3216.slaveAddress = AP3216_ADDRESS;
  res = i2c_master_transfer(I2C1, &ap3216);
  if (res) {
    printf("Read 失败 \r\n");
  }

  return data;
}

// 配置ap3216传感器
void AP3216_Init() {
  IOMUXC_SetPinMux(IOMUXC_UART4_TX_DATA_I2C1_SCL, 1);
  IOMUXC_SetPinMux(IOMUXC_UART4_RX_DATA_I2C1_SDA, 1);
  IOMUXC_SetPinConfig(IOMUXC_UART4_TX_DATA_I2C1_SCL, 0x70b0);
  IOMUXC_SetPinConfig(IOMUXC_UART4_RX_DATA_I2C1_SDA, 0x70b0);
  // 复位
  i2c_init(I2C1);
  AP3216_W_Data(AP3216_SYSTEM_CONFIGRATION_ADDRESS, 0x04);
  // 2.激活 ALS + PS+IR
  AP3216_W_Data(AP3216_SYSTEM_CONFIGRATION_ADDRESS, 0x03);
  // IIC_DELAY_MS(10);
  // 3.读取
  uint8_t ret = AP3216_R_Data(AP3216_SYSTEM_CONFIGRATION_ADDRESS);
  if (ret == 0x03) {
    printf("  ap3216 communication success!\r\n");
  }
}

// 读取ALS的数据 光
uint16_t AP3216_R_ALS() {
  // 3.读取数据
  uint16_t data = 0;
  uint8_t data_low = AP3216_R_Data(AP3216_ALS_DATA_LOW_ADDRESS);
  uint8_t data_high = AP3216_R_Data(AP3216_ALS_DATA_HIGH_ADDRESS);
  data = data_high << 8 | data_low;
  return data;
}

// 读取PS的数据 距离
uint16_t AP3216_R_PS() {
  // 3.读取数据
  uint16_t data = 0;
  uint8_t data_low = AP3216_R_Data(AP3216_PS_DATA_LOW_ADDRESS);
  uint8_t data_high = AP3216_R_Data(AP3216_PS_DATA_HIGH_ADDRESS);
  data = data_high & (0x3f);
  data <<= 4;
  data |= ((data_low) & 0xf);
  return data;
}
